package com.todo.biz.application.helper.detection;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.todo.biz.application.helper.detection.entity.*;
import com.todo.common.common.enums.BusinessSceneEnum;
import com.todo.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author azhebuxing
 * @date 2024/12/13 19:31
 * @description
 */
@Slf4j
@Component
public class AliyunDetectionHelper {

    public static final Integer MAX_TEXT_LENGTH = 600;

    @Resource
    private Client client;

    /**
     * 通用内容检测
     *
     * @param text
     */
    public TextDetectionResponse generalTextDetection(String text, Long bizId, BusinessSceneEnum sceneEnum) {
        TextModerationRequest textModerationRequest = new TextModerationRequest();
        textModerationRequest.setService("ai_art_detection");
        Map<String, String> parameters = new HashMap<>();
        if (text.length() > MAX_TEXT_LENGTH) {
            parameters.put("content", StringUtils.substring(text, 0, MAX_TEXT_LENGTH - 1));
        } else {
            parameters.put("content", text);
        }
        parameters.put("bizId", text);
        //parameters.put("deviceId", text);
        //parameters.put("deviceToken", text);    通过风险控制SDK获取到的设备令牌。
        textModerationRequest.setServiceParameters(JSONObject.toJSONString(parameters));
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);
            if (response == null || response.getBody() == null) {
                log.error("AliyunDetectionHelper#generalTextDetection 通用内容检测完成，返回结果为空 入参Biz:{},sceneEnum:{}", bizId, sceneEnum);
                //默认返回失败数据
                return null;
            }
            TextModerationResponseBody body = response.getBody();
            if (body.getCode() != 200 || body.getData() == null) {
                log.error("AliyunDetectionHelper#generalTextDetection 通用内容检测失败 入参Biz:{},sceneEnum:{},responseBody:{}", bizId, sceneEnum, JSONObject.toJSONString(body));
                return null;
            }
            TextModerationResponseBody.TextModerationResponseBodyData data = body.getData();
            TextDetectionResponse result = new TextDetectionResponse();
            result.setDeviceId(data.getDeviceId());
            result.setAccountId(data.getAccountId());
            result.setLabels(TextLabels.getByCode(data.getLabels()));
            result.setRequestId(body.getRequestId());
            TextDetectionResponse.Reason reason = new TextDetectionResponse.Reason();
            JSONObject jsonObject = JSONObject.parseObject(data.getReason());
            reason.setRiskLevel(TextRiskLevel.getByCode(jsonObject.getString("riskLevel")));
            reason.setRiskTips(jsonObject.getString("riskTips"));
            reason.setRiskWords(jsonObject.getString("riskWords"));
            result.setReason(reason);
            return result;
        } catch (Exception error) {
            log.error("AliyunDetectionHelper#generalTextDetection 通用内容检测异常，无法处理 bizId:{},sceneEnum:{}", bizId, sceneEnum, error);
        }
        return null;
    }


    /**
     * 评论内容检测
     *
     * @param text
     */
    public TextDetectionResponse commentTextDetection(String text, Long bizId, BusinessSceneEnum sceneEnum) {
        TextModerationRequest textModerationRequest = new TextModerationRequest();
        textModerationRequest.setService("comment_detection");
        Map<String, String> parameters = new HashMap<>();
        if (text.length() > MAX_TEXT_LENGTH) {
            parameters.put("content", StringUtils.substring(text, 0, MAX_TEXT_LENGTH - 1));
        } else {
            parameters.put("content", text);
        }
        parameters.put("bizId", text);
        //parameters.put("deviceId", text);
        //parameters.put("deviceToken", text);    通过风险控制SDK获取到的设备令牌。
        textModerationRequest.setServiceParameters(JSONObject.toJSONString(parameters));
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            TextModerationResponse response = client.textModerationWithOptions(textModerationRequest, runtime);
            if (response == null || response.getBody() == null) {
                log.error("AliyunDetectionHelper#commentTextDetection 评论内容检测完成，返回结果为空 入参Biz:{},sceneEnum:{}", bizId, sceneEnum);
                //默认返回失败数据
                return null;
            }
            TextModerationResponseBody body = response.getBody();
            if (body.getCode() != 200 || body.getData() == null) {
                log.error("AliyunDetectionHelper#commentTextDetection 评论内容检测失败 入参Biz:{},sceneEnum:{},responseBody:{}", bizId, sceneEnum, JSONObject.toJSONString(body));
                return null;
            }
            TextModerationResponseBody.TextModerationResponseBodyData data = body.getData();
            TextDetectionResponse result = new TextDetectionResponse();
            result.setDeviceId(data.getDeviceId());
            result.setAccountId(data.getAccountId());
            result.setLabels(TextLabels.getByCode(data.getLabels()));
            result.setRequestId(body.getRequestId());
            TextDetectionResponse.Reason reason = new TextDetectionResponse.Reason();
            JSONObject jsonObject = JSONObject.parseObject(data.getReason());
            reason.setRiskLevel(TextRiskLevel.getByCode(jsonObject.getString("riskLevel")));
            reason.setRiskTips(jsonObject.getString("riskTips"));
            reason.setRiskWords(jsonObject.getString("riskWords"));
            result.setReason(reason);
            return result;
        } catch (Exception error) {
            log.error("AliyunDetectionHelper#commentTextDetection 评论内容检测异常，无法处理 bizId:{},sceneEnum:{}", bizId, sceneEnum, error);
        }
        return null;
    }

    /**
     * 图片基线检测
     *
     * @param imgUrl
     * @param bizId
     * @param sceneEnum
     */
    public ImgDetectionResponse baseLineImgDetection(String imgUrl, Long bizId, BusinessSceneEnum sceneEnum) {
        // 检测参数构造。
        Map<String, String> serviceParameters = new HashMap<>();
        //公网可访问的URL。
        serviceParameters.put("imageUrl", imgUrl);
        //待检测数据唯一标识
        serviceParameters.put("dataId", UUID.randomUUID().toString());

        ImageModerationRequest request = new ImageModerationRequest();
        request.setService("baselineCheck");
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        RuntimeOptions runtime = new RuntimeOptions();
        try {
            ImageModerationResponse imageModerationResponse = client.imageModerationWithOptions(request, runtime);
            if (imageModerationResponse == null || imageModerationResponse.getBody() == null) {
                log.error("AliyunDetectionHelper#baseLineImgDetection 图片基线检测完成，返回结果为空 入参Biz:{},sceneEnum:{}", bizId, sceneEnum);
                //默认返回失败数据
                return null;
            }
            ImageModerationResponseBody body = imageModerationResponse.getBody();
            if (body.getCode() != 200 || body.getData() == null) {
                log.error("AliyunDetectionHelper#baseLineImgDetection 图片基线检测失败 入参Biz:{},sceneEnum:{},responseBody:{}", bizId, sceneEnum, JSONObject.toJSONString(body));
                return null;
            }
            ImageModerationResponseBody.ImageModerationResponseBodyData data = body.getData();
            ImgDetectionResponse result = new ImgDetectionResponse();
            result.setDataId(data.getDataId());
            result.setRequestId(body.getRequestId());
            result.setRiskLevel(ImgRiskLevel.getByCode(data.getRiskLevel()));
            List<ImgDetectionResponse.Result> results = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(data.getResult())) {
                List<ImageModerationResponseBody.ImageModerationResponseBodyDataResult> resultList = data.getResult();
                for (ImageModerationResponseBody.ImageModerationResponseBodyDataResult dataResult : resultList) {
                    ImgDetectionResponse.Result resposneResult = new ImgDetectionResponse.Result();
                    resposneResult.setConfidence(dataResult.getConfidence());
                    resposneResult.setLabel(dataResult.getLabel());
                    resposneResult.setDescription(dataResult.getDescription());
                    results.add(resposneResult);
                }
            }
            result.setResults(results);
            return result;
        } catch (Exception error) {
            log.error("AliyunDetectionHelper#baseLineImgDetection 图片基线检测异常，无法处理 bizId:{},sceneEnum:{}", bizId, sceneEnum, error);
        }
        return null;

    }
}
